package com.huaxin.hxcloud.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huamaitel.api.HMDefines;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.ScStationDTO;
import com.huaxin.common.message.MapHelper2;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.BottomSheetDialog;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.BigDeviceInfoActivity;
import com.huaxin.hxcloud.activity.ImageActivity;
import com.huaxin.hxcloud.activity.SVGShowActivity;
import com.huaxin.hxcloud.activity.StationRealDataActivity;
import com.huaxindata.common.util.HxLogUtils;
import com.huaxindata.im.main.share.ShareActivity;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatStationMessageBody;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author songxf
 * @date 2017/12/12
 * @Desc 首创重构站点界面
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxScStationInfoActivity extends BaseActivity {

    @BindView(R.id.address)
    ImageView    mAddress;
    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.station_img)
    ImageView    mStationImg;
    @BindView(R.id.station_name_tv)
    TextView     mStationNameTv;
    @BindView(R.id.principal_tv)
    TextView     mPrincipalTv;
    @BindView(R.id.principal_dex_tv)
    TextView     mPrincipalDexTv;
    @BindView(R.id.phone_dex_tv)
    TextView     mPhoneDexTv;
    @BindView(R.id.invest_dex_tv)
    TextView     mInvestDexTv;
    @BindView(R.id.scope_dex_tv)
    TextView     mScopeDexTv;
    @BindView(R.id.effluent_dex_tv)
    TextView     mEffluentDexTv;
    @BindView(R.id.water_dex_tv)
    TextView     mWaterDexTv;
    @BindView(R.id.collect_dex_tv)
    TextView     mCollectDexTv;
    @BindView(R.id.send_dex_tv)
    TextView     mSendDexTv;
    @BindView(R.id.video_tv)
    TextView     mVideoTv;
    @BindView(R.id.scene_tv)
    TextView     mSceneTv;
    @BindView(R.id.tv_station_target)
    TextView     mTvStationTarget;
    @BindView(R.id.device_svg_tv)
    TextView     mDeviceSvgTv;
    @BindView(R.id.share)
    ImageView    mShare;
    @BindView(R.id.cardview)
    CardView     mCardview;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerview;


    private String                 mStationCode;
    private HxScStationInfoAdapter mStationInfoAdapter;
    private Handler                mHandler;
    //华迈视频 回调状态
    private static final int EVENT_CONNECT_SUCCESS = 1;
    private static final int EVENT_CONNECT_FAIL    = 2;
    private static final int EVENT_LOGIN_SUCCESS   = 3;
    private static final int EVENT_LOGIN_FAIL      = 4;
    private ScStationDTO.DataBean mStationBean;
    private int                   mStationType;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_scstation_info;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    public static void start(Context context, String stationCode) {
        Intent intent = new Intent(context, HxScStationInfoActivity.class);
        intent.putExtra(Constants.IK_STATION_CODE, stationCode);
        context.startActivity(intent);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_STATION_CODE)) {
            mStationCode = extras.getString(Constants.IK_STATION_CODE);
        } else {
            finish();
        }

        if (extras.containsKey(Constants.IK_STATION_TYPE)) {
            mStationType = extras.getInt(Constants.IK_STATION_TYPE);
        }
    }

    @Override
    public void initView() {
        setSupportActionBar(mToolbar);
        mShare.setImageResource(R.drawable.icon_share);
        mAddress.setImageResource(R.drawable.route);
        mShare.setVisibility(View.INVISIBLE);
        //碧水源显示站点指标
       /* if (Constant.BSYorgCodeFirst.equals(UserManager.getFirstOrgCode())) {
            tv_station_target.setVisibility(View.VISIBLE);
        } else {
            tv_station_target.setVisibility(View.GONE);
        }*/
        initRecyclerView();
        registerHander();
    }


    private void initRecyclerView() {
        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerview.setHasFixedSize(true);
        mStationInfoAdapter = new HxScStationInfoAdapter(this);
        mRecyclerview.setAdapter(mStationInfoAdapter);
        mStationInfoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ScStationDTO.DataBean.DeviceListBean listBean = mStationInfoAdapter.getData().get(position);
                Intent intent;
                switch (view.getId()) {
                    case R.id.device_realdata_tv://指标
                        intent = new Intent(HxScStationInfoActivity.this, HxStationInfoActivity
                                .class);
                        intent.putExtra(Constants.IK_DEVICE_CODE, listBean.getDeviceCode());
                        intent.putExtra("STATION_CODE", mStationCode);
                        startActivity(intent);
                        break;
                    case R.id.device_svg_tv: //工艺图
                        intent = new Intent(HxScStationInfoActivity.this, SVGShowActivity.class);
                        intent.putExtra(Constants.IK_DEVICE_CODE, listBean.getDeviceCode());
                        intent.putExtra(Constants.IK_STATION_CODE, mStationCode);
                        startActivity(intent);
                        break;
                    case R.id.item_view:
                        BigDeviceInfoActivity.start(HxScStationInfoActivity.this, listBean.getDeviceCode());
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void requestData() {
        ApiGetStationInfo(mStationCode);
    }

    private void ApiGetStationInfo(String stationCode) {
        updateLoadStatus(LOADING);
        Call<ScStationDTO> call1 = HxTransmitRequestHelper.getRequestApi().getScStationInfo(stationCode);
        call1.enqueue(new Callback<ScStationDTO>() {
            @Override
            public void onResponse(Call<ScStationDTO> call, Response<ScStationDTO> response) {
                mStationBean = response.body().getData();
                if (response.isSuccessful() && mStationBean != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    updateView(mStationBean);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ScStationDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
                HxLogUtils.i("------>" + t);
            }
        });
    }

    /**
     * 添加视图数据
     *
     * @param stationBean
     */
    private void updateView(ScStationDTO.DataBean stationBean) {
        mShare.setVisibility(View.VISIBLE);
        //title
        mToolbar.setTitle(stationBean.getStationName());
        //站点urlsx
        loadNetImg(mStationImg, stationBean.getStationImg());
        //站点名字
        loadText(mStationNameTv, stationBean.getStationName());
        //所属企业
        //loadText(mFirmDexTv, stationBean.getOrgName(), "暂无");
        //所属区域
        //loadText(mAreaDexTv, stationBean.getAddress(), "暂无");
        //负责人
        loadText(mPrincipalDexTv, stationBean.getContactPerson(), "暂无");
        //联系方式
        loadText(mPhoneDexTv, stationBean.getContactPhone(), "暂无");
        //处理能力
      /*  if (Util.checkNull(stationBean.getProcessCapacity())) {
            loadText(mPowerDexTv, "暂无");
        } else {
            loadText(mPowerDexTv, stationBean.getProcessCapacity() + "(吨/天)");
        }*/
        //服务人数
        //loadText(mServiceDexTv, stationBean.getServicePeople() + "人");
        //厂站投资
        loadText(mInvestDexTv, stationBean.getStationCost() + "万", "未知");
        //服务范围
        loadText(mScopeDexTv, stationBean.getServicePeople() + "户");
        /*出水要求
        1：国标一级a
        2：国标一级b
        3：京标a
        4：京标b
        5：其他*/
        String watreStandard = null;
        switch (stationBean.getWaterStandard()) {
            case 1:
                watreStandard = "国标一级A";
                break;
            case 2:
                watreStandard = "国标一级B";
                break;
            case 3:
                watreStandard = "京标A";
                break;
            case 4:
                watreStandard = "京标A";
                break;
            case 0:
            default:
                watreStandard = "其他";
                break;
        }
        loadText(mEffluentDexTv, watreStandard + "");

        //水量
        loadText(mWaterDexTv, stationBean.getWaterCapacity() + "m3/h");
        //采集频率
        loadText(mCollectDexTv, stationBean.getReadCycle() + "分/次");
        //发送频率
        loadText(mSendDexTv, stationBean.getSendCycle() + "分/次");
        //adapter添加数据
        stationBean.getDeviceList();
        mStationInfoAdapter.setNewData(stationBean.getDeviceList());
    }

    private void registerHander() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case EVENT_LOGIN_SUCCESS:
                        // ToastUtil.showToast("登录成功");

                        Intent intent = new Intent(HxScStationInfoActivity.this, HxHuaMaiVideoActivity.class);
                        intent.putExtra("stationCode", mStationCode);
                        startActivity(intent);
                        break;
                    case EVENT_LOGIN_FAIL:
                        BaseApp.getJni().disconnectServer(BaseApp.serverId);
                        //  ToastUtil.showToast("登录失败");
                        break;
                    case EVENT_CONNECT_SUCCESS:
                        int result = BaseApp.getJni().getDeviceList(BaseApp.serverId);
                        if (result != HMDefines.HMEC_OK) {
                            sendEmptyMessage(EVENT_LOGIN_FAIL);
                            return;
                        }
                        // step 2: Get user information.
                        HMDefines.UserInfo userInfo = BaseApp.getJni().getUserInfo(BaseApp.serverId);
                        if (userInfo == null) {
                            sendEmptyMessage(EVENT_LOGIN_FAIL);
                            return;
                        }

                        // step 3: Get transfer service.
                        // if (userInfo.useTransferService != 0&&userInfo.useTransferService !=8) {
                        if (userInfo.useTransferService != 0) {
                            result = BaseApp.getJni().getTransferInfo(BaseApp.serverId);
                            if (result != HMDefines.HMEC_OK) {
                                sendEmptyMessage(EVENT_LOGIN_FAIL);
                                return;
                            }
                        }

                        // step 4: Get tree id.
                        BaseApp.treeId = BaseApp.getJni().getTree(BaseApp.serverId);
                        sendEmptyMessage(EVENT_LOGIN_SUCCESS);
                        break;
                    case EVENT_CONNECT_FAIL:
                        //提示登录失败原因
                        ToastUtil.showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @OnClick({R.id.scene_tv, R.id.video_tv, R.id.share, R.id.tv_station_target, R.id.address,R.id.device_svg_tv})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {

            case R.id.scene_tv://现场图片
                ImageActivity.showStationImg(this, mStationBean.getStationCode());
                break;
            case R.id.video_tv:////华迈视频(互联网观看视频)
                initHuaMai();
                break;
            case R.id.share:
                final String code = mStationBean.getStationCode();
                final String name = mStationBean.getStationName();
                final String status = "" + mStationBean.getStationState();
                final String address = TextUtils.isEmpty(mStationBean.getAddress()) ? " " : mStationBean
                        .getAddress();
                final String image = TextUtils.isEmpty(mStationBean.getStationImg()) ? " " : mStationBean.getStationImg();
                //  String[] message = new String[]{ChatMessageBody.Type.STATION + "", code, name, status, address, image};
                ChatStationMessageBody stationMessageBody = new ChatStationMessageBody(ChatMessageBody.Type.STATION, code, name, status, address, image);
                final Intent intentShare = new Intent(this, ShareActivity.class);
                intentShare.putExtra("message_type", ChatMessageBody.Type.STATION);
                intentShare.putExtra("message", stationMessageBody);
                startActivity(intentShare);
                break;
            case R.id.tv_station_target://指标站点
                intent = new Intent(HxScStationInfoActivity.this, StationRealDataActivity.class);
                intent.putExtra(Constants.IK_DEVICE_CODE, mStationCode);
                intent.putExtra("STATION_CODE", mStationCode);
                startActivity(intent);

                break;
            case R.id.address://定位路径
                final String[] array = {"腾讯地图", "百度地图", "高德地图"};
                double lng = mStationBean.getLng();
                double lat = mStationBean.getLat();
                final String stationName = mStationBean.getStationName();
                final LatLng endlatLng = new LatLng(lat, lng);
                BottomSheetDialog dialog = new BottomSheetDialog(this, array, new
                        BottomSheetDialog.OnItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                if (position == 0) {
                                    HxLogUtils.i("腾讯地图");
                                    MapHelper2.startNavi(0, BaseApp.getLatLng(), BaseApp.getAddrStr(), endlatLng, stationName, HxScStationInfoActivity.this);
                                } else if (position == 1) {
                                    MapHelper2.startNavi(1, BaseApp.getLatLng(), BaseApp.getAddrStr(), endlatLng, stationName, HxScStationInfoActivity.this);
                                    HxLogUtils.i("百度地图");
                                } else if (position == 2) {
                                    MapHelper2.startNavi(2, BaseApp.getLatLng(), BaseApp.getAddrStr(), endlatLng, stationName, HxScStationInfoActivity.this);
                                    HxLogUtils.i("高德地图");
                                }
                            }

                        });
                if (!TextUtils.isEmpty(BaseApp.getLatLng() + "") && !TextUtils.isEmpty(endlatLng + "") && !TextUtils.isEmpty(stationName)) {
                    dialog.show();
                } else {
                    ToastUtil.showToast("站点信息不全,无法定位");
                }
                break;
            case R.id.device_svg_tv: //工艺图
                intent = new Intent(HxScStationInfoActivity.this, SVGShowActivity.class);
                intent.putExtra(Constants.IK_DEVICE_CODE, "");
                intent.putExtra(Constants.IK_STATION_CODE, mStationCode);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * @desc 华迈视频相关初始化
     * @author songxf
     * created at 2017/12/13 16:03
     */
    HMDefines.LoginServerInfo mInfo;

    private void initHuaMai() {
        Thread serverThread = new Thread() {
            @Override
            public void run() {
                mInfo = new HMDefines.LoginServerInfo();
                mInfo.ip = "www.huamaiyun.com";//平台地址
                mInfo.port = 80; //平台端口
                mInfo.user = "hxsj";//用户名
                mInfo.password = "123456";//密码
                mInfo.model = android.os.Build.MODEL; // 手机型号
                mInfo.version = android.os.Build.VERSION.RELEASE; // 手机系统版本号
                String error = jni_connectServer();
                if (error != null) {
                    sendEmptyMessage(EVENT_CONNECT_FAIL, error);
                } else {
                    sendEmptyMessage(EVENT_CONNECT_SUCCESS);
                }
                super.run();
            }

        };
        serverThread.start();
    }

    public String jni_connectServer() {
        StringBuilder error = new StringBuilder();
        Log.d(TAG, "jni_connectServer: ---->" + mInfo);
        BaseApp.serverId = BaseApp.getJni().connectServer(mInfo, error);
        if (BaseApp.serverId == -1) {
            return error.toString();
        }
        return null;
    }


    private void sendEmptyMessage(int msgId, String error) {
        if (mHandler == null) {
            return;
        }
        Message msg = new Message();
        msg.what = msgId;
        msg.obj = error;
        mHandler.sendMessage(msg);
    }

    private void sendEmptyMessage(int msgId) {
        sendEmptyMessage(msgId, null);
    }

}
